<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 分销员管理
 *
 * @icon fa fa-circle-o
 */
class AgentUser extends Backend
{

    
    protected $model = null;
    protected $searchFields = 'name';
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $fxms="";
            try{
                $fxms=\Tools\Config::getAgentFmxs();
            }catch(\Exception $e){
                $this->error($e->getMessage());
            }
            $this->assignconfig("fxms",$fxms);
            return $this->view->fetch();
        }
        $fxms="";
        try{
            $fxms=\Tools\Config::getConfig(null,"agent","fxms");
        }catch(\Exception $e){
            $this->error($e->getMessage());
        }
        $cate = $this->request->param("cate","");
        if($cate=="info"){
            $data=[];
          
            $fxrs=0;
            if($fxms==1){
                $fxrs=Db::name("deerhome_user")->count();
            }else{
                $fxrs=Db::name("deerhome_user")->where("agent",1)->count();
            }
            array_push($data,[
                'icon'=>'icon-zhanghao',
                'name'=>'分销员人数',
                'num'=>$fxrs
            ]);
            array_push($data,[
                'icon'=>'icon-fuwurenyuanguanli',
                'name'=>'推广用户数',
                'num'=>Db::name("deerhome_user")->where('agent_lev1_uid','>',0)->count()
            ]);
            array_push($data,[
                'icon'=>'icon-xiangmugaikuang_0',
                'name'=>'分销订单',
                'num'=>Db::name("deerhome_order")->where('agent_lev1_uid','>',0)->where("status","in",[2,3,4,5])->count()
            ]);
            $price=Db::name("deerhome_order")->where('agent_lev1_uid','>',0)->where("status","in",[2,3,4,5])->SUM('price_payed');
            array_push($data,[
                'icon'=>'icon-a-yingxiaobaoxiao2',
                'name'=>'订单金额',
                'num'=>number_format($price,2)
            ]);
            $wallet_left=Db::name("deerhome_user")->SUM('wallet_left');
            array_push($data,[
                'icon'=>'icon-xindaieduye-xindaiedugaikuang',
                'name'=>'佣金余额',
                'num'=>number_format($wallet_left,2)
            ]);
            $this->success('','',$data);
        }
        
        $filter = $this->request->request("filter","{}");
        $filter=json_decode($filter,true);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where=[];
        foreach($filter as $k=>$v){
            if($k=="regtime"){
                $v=explode(" - ",$v);
                if(count($v)==2){
                    $where['u.regtime']=['between',[$v[0],$v[1]]];
                }
            }
            if($k=="utel"){
                $where['u.utel|u.uname']=['LIKE',"%{$v}%"];
            }
            if($k=="agent_lev_id"){
                $where['u.agent_lev_id']=['=',$v];
            }
        }
        if($fxms==2){
            $where['u.agent']=1;
        }
        $list=Db::name("deerhome_user")->alias('u')
        ->join("deerhome_agent_lev a","a.id=u.agent_lev_id","left")
        ->join("deerhome_user u2","u2.id=u.agent_lev1_uid","left")
        ->field("u.*,a.name,u2.uname as lev1_uname")
        ->where($where)
        ->order("u.id desc")->paginate($limit);
        $rows=$list->items();
        foreach($rows as $k=>&$v){
            $v['my_users']=Db::name("deerhome_user")->where('agent_lev1_uid',$v['id'])->count();
            $v['order_price']=Db::name("deerhome_order")->where('jz_user_id',$v['id'])->SUM('price_payed');
            $v['order_price'] = number_format($v['order_price'],2);

            $wallet_dj_lev1=Db::name("deerhome_order")->where('status','in',[2,3,4,5])->where('agent_lev1_price_js',2)->where('agent_lev1_uid',$v['id'])->SUM('agent_lev1_price');
            $wallet_dj_lev2=Db::name("deerhome_order")->where('status','in',[2,3,4,5])->where('agent_lev2_price_js',2)->where('agent_lev2_uid',$v['id'])->SUM('agent_lev2_price');
            $v['wallet_dj']=bcadd($wallet_dj_lev1,$wallet_dj_lev2,2);
            $v['wallet_dj'] = number_format($v['wallet_dj'],2);
            $v['utel']=\Tools\Config::tel($v['utel']);
        }
        $result = ['total' => $list->total(), 'rows' => $rows];
        return json($result);
    }
    /**
     * 添加分销员
    */
    public function add(){
        $ac=$this->request->param("ac","");
        if($ac=='ulist'){
            $name=$this->request->param("name","");
            $where=[];
            $where['agent']=2;
            $where['utel']=['exp',Db::raw("IS NOT NULL")];
            if($name){
                $where['uname|utel']=['LIKE',"%{$name}%"];
            }
            $list=Db::name("deerhome_user")->field("id,CONCAT_WS(' / ',uname,utel) as name")->where($where)->order("id desc")->select();
            echo json_encode(['list'=>$list,'total'=>count($list)]);
            exit;
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $uid=$this->request->param("uid",0,'intval');
        Db::name("deerhome_user")->where('id',$uid)->update([
            'agent'=>1
        ]);
        $this->success();
    }
    /**
     * 移除分销员
    */
    public function del($ids = null){
        $ids = $this->request->param("ids/a");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        foreach($ids as $k=>$v){
            Db::name("deerhome_user")->where('id',$v)->update([
                'agent'=>2
            ]);
        }
        $this->success();
    }
    /**
     * 设置等级
    */
    public function set_lev(){
        $id=$this->request->param("ids",0,'intval');
        $lev=$this->request->param("lev",0,'intval');
        $row = Db::name("deerhome_agent_lev")->where('id',$lev)->find();
        if (!$row) {
            $lev=0;
        }
        Db::name("deerhome_user")->where('id',$id)->update([
            'agent_lev_id'=>$lev
        ]);
        $this->success("设置成功");
    }
    /**
     * 详情
    */
    public function detail(){
        
        $id=$this->request->param("ids",0,'intval');

        $row = Db::name("deerhome_user")->where('id',$id)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $table=$this->request->param("table");
        //推广用户表格
        if($table=="user"){
            return $this->table_user($id);
        }
        //推广订单
        if($table=="order"){
            return $this->table_order($id);
        }
        //推广佣金明细
        if($table=="money"){
            return $this->table_money($id);
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['levTxt']="无";

        $levList=Db::name("deerhome_agent_lev")->field("id,name,lev")->order("lev asc")->select();
        foreach($levList as $k=>$v){
            if($v['id']==$row['agent_lev_id']){
                $row['levTxt']=$v['name'];
            }
        }


        $row['lev1']="平台直推";
        $lev1=Db::name("deerhome_user")->where('id',$row['agent_lev1_uid'])->find();
        if($lev1){
            $row['lev1']="UID{$lev1['id']}/".$lev1['uname'];
        }
        $row['wallet_on_way']=0;

        $wallet_dj_lev1=Db::name("deerhome_order")->where('status','in',[2,3,4,5])->where('agent_lev1_price_js',2)->where('agent_lev1_uid',$id)->SUM('agent_lev1_price');
        $wallet_dj_lev2=Db::name("deerhome_order")->where('status','in',[2,3,4,5])->where('agent_lev2_price_js',2)->where('agent_lev2_uid',$id)->SUM('agent_lev2_price');
        $row['wallet_on_way']=bcadd($wallet_dj_lev1,$wallet_dj_lev2,2);
        $row['wallet_on_way'] = number_format($row['wallet_on_way'],2);



        $row['wallet_txz']=Db::name("deerhome_worker_money_log")->where("status",1)->where("type","分销提现")->where('deerhome_user_id',$id)->SUM('price');
        $row['wallet_txz']*=-1;
        $row['wallet_txz'] = number_format($row['wallet_txz'],2);

        $row['wallet_ljtx']=Db::name("deerhome_worker_money_log")->where("status",2)->where("type","分销提现")->where('deerhome_user_id',$id)->SUM('price');
        $row['wallet_ljtx']*=-1;
        $row['wallet_ljtx'] = number_format($row['wallet_ljtx'],2);
        $row['utel']=\Tools\Config::tel($row['utel']);
        if (false === $this->request->isPost()) {
            $this->view->assign('levList', $levList);
            $this->assignconfig('levList', $levList);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        
        $this->success();
    }
    /**
     * 推广用户表格
     * */
    private function table_user($uid){
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where=[];
        $where['agent_lev1_uid']=$uid;
        $list=Db::name("deerhome_user")->where($where)->order("id desc")->paginate($limit);
        $rows=$list->items();
        foreach($rows as $k=>&$v){
            $v['order_num']=0;
            $v['order_price']=0;
            $order=Db::name("deerhome_order")->where('jz_user_id',$v['id'])->where('agent_lev1_uid|agent_lev2_uid',$uid)->where("status","in",[2,3,4,5])->field("count(id) as order_num,SUM(price_payed) as order_price")->find();
            if($order){
                $v['order_num']=$order['order_num'];
                $v['order_price']=$order['order_price'];
            }

            $v['order_price'] = number_format($v['order_price'],2);
        }
        $result = ['total' => $list->total(), 'rows' => $rows];
        return json($result);
    }
    /**
     * 推广分销订单
     * */
    private function table_order($uid){

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where=[];
        $where['o.status']=['in',[2,3,4,5]];
        $where['o.agent_lev1_uid|o.agent_lev2_uid']=$uid;
        $list=Db::name("deerhome_order")->alias("o")->join("deerhome_user u","u.id=o.jz_user_id","left")->field("o.*,u.uname")->where($where)->order("o.id desc")->paginate($limit);
        $rows=$list->items();
        
        $result = ['total' => $list->total(), 'rows' => $rows];
        return json($result);
    }
    /**
     * 佣金明细
     * */
    private function table_money($uid){
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where=[];
        $where['type']=['in',['分销分佣','分销提现']];
        $where['deerhome_user_id']=$uid;
        $list=Db::name("deerhome_worker_money_log")->where($where)->order("id desc")->paginate($limit);
        $rows=$list->items();
        
        $result = ['total' => $list->total(), 'rows' => $rows];
        return json($result);
    }
}
